package com.bigegg.employee.service.impl;

import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.bigegg.employee.domain.RegisterInfo;
import com.bigegg.employee.domain.TypeUserInfo;
import com.bigegg.employee.service.TypeUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;


/**
 * 用户 Service
 *
 * @author sun
 */
@Service
public class CUserService {


    @Autowired
    private List<TypeUserService> typeUserServices;

    /**
     * 获取用户类型代码
     *
     * @param user 登录用户
     * @return 代码
     */
    public int getUserTypeCode(LoginUser user) {
        TypeUserService service = getTypeUserService(user);
        return service.getType();
    }

    /**
     * 获取用户类型service
     *
     * @param user 登录用户
     * @return service
     */
    private TypeUserService getTypeUserService(LoginUser user) {
        List<String> roleNames = user.getUser().getRoles().stream().map(SysRole::getRoleName).collect(Collectors.toList());
        //  获取用户的type代码
        for (TypeUserService typeUserService : typeUserServices) {
            if (roleNames.stream().anyMatch(typeUserService::support)) {
                return typeUserService;
            }
        }
        throw new RuntimeException("不支持的用户类型。");
    }

    /**
     * 获取用户类型service
     *
     * @param type 登录用户类型
     * @return service
     */
    private TypeUserService getTypeUserService(int type) {
        //  获取用户的type代码
        for (TypeUserService typeUserService : typeUserServices) {
            if (type == typeUserService.getType()) return typeUserService;
        }
        throw new RuntimeException("不支持的用户类型。");
    }

    // 获取所有用户类型名称
    String[] getUserTypeNames() {
        return typeUserServices.stream().map(TypeUserService::getTypeName).toArray(String[]::new);
    }


    /**
     * 获取用户基本信息
     *
     * @param loginUser 登录用户
     * @return 基本信息
     */
    public TypeUserInfo getUserInfo(LoginUser loginUser) {
        TypeUserService service = getTypeUserService(loginUser);
        return service.getLoginUserInfo(loginUser.getUser());
    }

    public TypeUserInfo getUserInfo(Long typeUserId, int type) {
        TypeUserService service = getTypeUserService(type);
        return service.getTypeUserInfo(typeUserId);
    }


    /**
     * 注册用户
     *
     * @param type 用户类型
     * @param info 注册信息
     */
    @Transactional(rollbackFor = Exception.class)
    public void registerTypeUser(int type, RegisterInfo info) {
        TypeUserService service = getTypeUserService(type);
        service.register(info);
    }

}
